package com.alingrad.iou;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

public class ActionBar extends FrameLayout {
	private View mTitle;
	private View mNewTransactionButton;
	private OnClickListener mClickListener;
	
	public ActionBar(Context context) {
		this(context, null, 0);
	}

	public ActionBar(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ActionBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setView(R.layout.action_bar);
		TypedArray a = getContext().obtainStyledAttributes(attrs, 
				R.styleable.ActionBar);
		mClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (v == mTitle)
					goToDashboard();
				if (v == mNewTransactionButton)
					onNewTransactionButtonPressed();
			}
		};
		mTitle = findViewById(R.id.action_bar_title);
		mNewTransactionButton = findViewById(R.id.action_bar_new_transaction);
		if (!a.getBoolean(R.styleable.ActionBar_disable_title_button, false))
			mTitle.setOnClickListener(mClickListener);
		if (!a.getBoolean(R.styleable.ActionBar_disable_new_transaction_button, false))
			mNewTransactionButton.setOnClickListener(mClickListener);
		else
			mNewTransactionButton.setVisibility(View.GONE);
	}	
	
	private void onNewTransactionButtonPressed() {
		Intent i = new Intent(getContext(), NewTransactionActivity.class);
		i.setAction(NewTransactionActivity.ACTION_NEW);
		getContext().startActivity(i);
	}
	
	private void goToDashboard() {
		Intent i = new Intent(getContext(), DashboardActivity.class);
		getContext().startActivity(i);
	}
	
	public View setView(int resId) {
		LayoutInflater li = LayoutInflater.from(getContext());
		View view = li.inflate(resId, this, true);
		return view;
	}

}
